/*
 * $Header: /opt/javacvs/bk/src/main/java/com/uusee/framework/util/page/PageHelper.java,v 1.1 2009/04/02 10:08:52 wangrui Exp $
 * $Revision: 1.1 $
 * $Date: 2009/04/02 10:08:52 $
 * ============================================================================
 *
 * Copyright (c) 2008 Beijing uusee Tech CO.,  All rights reserved.
 *
 * ============================================================================
 */
package com.uusee.framework.util.page;

/**
 * 分页信息帮助类
 * 
 * @author duyi
 * 
 * Create Time: 2008-3-26 上午10:11:18
 */
public class PageHelper {
	/**
	 * 通过给定的页码,每页实体数量,实体总数量来填充PageInfo类.
	 * 
	 * @param pageNo 页码
	 * @param pageSize 每页实体数量
	 * @param totalResult 实体总数量
	 * @return
	 * @throws PageException
	 */
	public static PageInfo fillPageInfo(int pageNo, int pageSize, long totalResult) {
		// new 一个新的page对象
		PageInfo page = new PageInfo();

		// 取总页数
		int totalPage = (int) (((totalResult % pageSize) == 0) ? (totalResult / pageSize)
				: (totalResult / pageSize + 1));

		// 校验页码,如果超出范围,则重新设置
		if (pageNo >= totalPage) {
			pageNo = totalPage;
			page.setOnLastPage(true);
		} else {
			page.setOnLastPage(false);
		}
		// 校验页码,如果超出范围,则重新设置
		if (pageNo <= 1) {
			pageNo = 1;
			page.setOnFirstPage(true);
		} else {
			page.setOnFirstPage(false);
		}

		// 计算当前页首记录的游标值
		int firstResult = (pageNo - 1) * pageSize;

		int lastResult = -1;
		if (totalResult % pageSize == 0) {
			lastResult = (int) (pageNo != totalPage ? firstResult + pageSize : firstResult + pageSize);
		} else {
			lastResult = (int) (pageNo != totalPage ? firstResult + pageSize : firstResult + totalResult % pageSize);
		}

		// 填充PageInfo的值
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setTotalPage(totalPage);
		page.setTotalResult(totalResult);
		page.setFirstResult(firstResult);
		page.setLastResult(lastResult);

		return page;
	}
}
